package com.qf.md.controller;

import com.qf.common.annotation.Log;
import com.qf.common.core.controller.BaseController;
import com.qf.common.core.domain.AjaxResult;
import com.qf.common.core.page.TableDataInfo;
import com.qf.common.enums.BusinessType;
import com.qf.md.domain.MdUnitMeasure;
import com.qf.md.service.IMdUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * --- 天道酬勤 ---
 *
 * @author GUOFUCHENG
 * @date 2025/8/28
 * @desc
 */
@RestController
@RequestMapping("/md/unit")
public class MdUnitController extends BaseController {
    @Autowired
    private IMdUnitService mdunitService;

    @GetMapping("/list")
    public TableDataInfo list(MdUnitMeasure mdUnitMeasure) {
        startPage();
        List<MdUnitMeasure> list = mdunitService.list(mdUnitMeasure);
        // System.out.println("list = " + list);
        return getDataTable(list);
    }


    /**
     * 查所有主计量单位列表
     */
    @GetMapping("/listPrimaryUnit")
    public AjaxResult listPrimaryUnit(MdUnitMeasure mdUnitMeasure) {
        List<MdUnitMeasure> list = mdunitService.selectPrimaryUnitList(mdUnitMeasure);
        return success(list);
    }

    /**
     * 添加计量单位
     */

    @PostMapping
    public AjaxResult add(@RequestBody MdUnitMeasure mdUnitMeasure) {
        //添加前先检查单位名是否存在
        if (mdunitService.checkUnitNameUnique(mdUnitMeasure)) {
            return error("新增单位'" + mdUnitMeasure.getMeasureName() + "'失败，单位名称已存在");
        } else if (mdunitService.checkUnitCodeUnique(mdUnitMeasure)) {//检查单位编码是否唯一
            return error("新增单位'" + mdUnitMeasure.getMeasureCode() + "'失败，单位编码已存在");
        }
        //添加
        mdUnitMeasure.setCreateBy(getUsername());
        mdUnitMeasure.setCreateTime(new Date());
        //如果不重复,再添加
        int n = mdunitService.insertMdUnitMeasure(mdUnitMeasure);
        return AjaxResult.success(n);
    }
}
